/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By zhanglin
* 注意：
* 本软件为zhanglin开发研制
 */
package model

import (
	"shop/global"
	"time"
)

type IRole interface {
	InsertRole() (int64, error)
	DeleteRole(id int64) error
	UpdateRole() error
	FindRoleList() (interface{}, error)
	SplitPageRoleList(pageIndex int64, pageSize int64) (interface{}, error)
	FindRoleByUserIdList(userId int64) ([]Role, error)
}

/**
	Role实体对象
 **/
type Role struct {
	Id int64 `json:"id" gorm:"primary_key"` //ID

	Name string `json:"name"` //名称

	Remark string `json:"remark"` //备注

	DataScope string `json:"data_scope"` //数据权限

	Level int32 `json:"level"` //角色级别

	CreateTime time.Time `json:"create_time"` //创建日期

	Permission string `json:"permission"` //功能权限
}

func (vo *Role) InsertRole() (int64, error) {
	table := global.GDB.Table("role")
	if err := table.Create(&vo).Error; err != nil {
		return 0, err
	}

	return vo.Id, nil
}

func (vo *Role) DeleteRole(id int64) error {
	table := global.GDB.Table("role")
	table = table.Where("id = ?", id)
	if err := table.Delete(Role{}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *Role) UpdateRole() error {

	table := global.GDB.Table("role")
	table = table.Where("id = ?", vo.Id)
	if err := table.Updates(map[string]interface{}{
		"id": vo.Id, "name": vo.Name, "remark": vo.Remark, "data_scope": vo.DataScope, "level": vo.Level, "create_time": vo.CreateTime, "permission": vo.Permission}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *Role) FindRoleList() ([]Role, error) {
	var lists []Role
	table := global.GDB.Table("role")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}

func (vo *Role) SplitPageRoleList(pageIndex int64, pageSize int64) (interface{}, error) {
	var lists []Role
	var total int64
	table := global.GDB.Table("role")
	table = table.Select("  id,   name,   remark,   data_scope,   level,   create_time,   permission   ")
	if err := table.Count(&total).Error; err != nil {
		return lists, err
	}
	table = table.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}

	m := make(map[string]interface{})
	m["lists"] = lists
	m["total"] = total
	return m, nil
}

func (vo *Role) FindRoleByUserIdList(userId int64) ([]Role, error) {
	var lists []Role

	table := global.GDB.Table("role r").Joins("LEFT JOIN users_roles ur ON ur.role_id = r.id ").Where("ur.user_id = ?", userId)
	table = table.Select(" r.* ")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}
